//
//  MQMusicListViewController.m
//  MQ
//
//  Created by lanou on 15/10/28.
//  Copyright © 2015年 徐永祥. All rights reserved.
//

#import "MQMusicListViewController.h"
#import "PKRequestManager.h"
#import "MQMusicDetailModel.h"
#import "MQMusicDetailCell.h"
#import "PKPlayerManger.h"
#import "MQMusicPlayView.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
@interface MQMusicListViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;
@property (nonatomic, strong) NSMutableDictionary *parDic;
@property (nonatomic, strong) NSMutableArray *musicURLArr;
@property (nonatomic, strong) MQMusicPlayView *playView;
@property (nonatomic, assign) BOOL playState;
@property (nonatomic, assign) NSUInteger *playTime;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSUInteger currentIndex;

@end

@implementation MQMusicListViewController
- (NSMutableArray *)dataSourceArr{
    if (_dataSourceArr == nil) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}
- (NSMutableArray *)musicURLArr{
    if (_musicURLArr == nil) {
        _musicURLArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _musicURLArr;
}
- (void)requestData{
    self.parDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _parDic[@"resid"] = [NSString stringWithFormat:@"%lld", self.myID];
    _parDic[@"sign"] = @"0a2c58496eb4c02ad44f0ad0551f700e";
    _parDic[@"method"] = @"get_user_song_single_details";
    _parDic[@"imsi"] = @"460012676617727";
    _parDic[@"sid"] = @"244918960";
    _parDic[@"protocolCode"] = @"2.0";
    _parDic[@"size"] = @"20";
    _parDic[@"timestamp"] = @"20151028022447";
    _parDic[@"page"] = @"1";
    
    [PKRequestManager requestWithType:POST urlString:@"http://client.ctmus.cn/iting2/imusic/V2" parDic:_parDic finish:^(NSData *data) {
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
    
    for (NSDictionary *dic1 in dic[@"data"][@"songlist"]) {
        MQMusicDetailModel *model = [[MQMusicDetailModel alloc] init];
        [model setValuesForKeysWithDictionary:dic1];
        [self.dataSourceArr addObject:model];
        [self.musicURLArr addObject:[model.qqInfo.qq_url_list[0] url]];
    }
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        [def setObject:self.musicURLArr forKey:@"musicURL"] ;
    [[PKPlayerManger shareManger] setMangerMusicArray:self.musicURLArr];
    
    // 进入时播放器默认显示第一首歌曲信息,并且加以播放
    MQMusicDetailModel *model = self.dataSourceArr[0];
    [_playView configureViewWithModel:model];
    model.isSelected = YES;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self tableView:self.mainTableView didSelectRowAtIndexPath:indexPath];
    
    [self.mainTableView reloadData];
       
        
    } error:^(NSError *error) {
        NSLog(@"解析失败 %@", [error localizedDescription]);
    }];

    
}
//- (void)viewWillDisappear:(BOOL)animated{
//    [[PKPlayerManger shareManger] stop];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *musicBackGround = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [musicBackGround setImage:[UIImage imageNamed:@"cellbackground"]];
    [self.view addSubview:musicBackGround];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.navigationItem.title = self.title;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self requestData];
    
   // 添加播放视图
    _playView = [[MQMusicPlayView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 250)];
    _playView.musicListVC = self;
    [_playView.beforeBtn addTarget:self action:@selector(didClickBeforeBtn) forControlEvents:(UIControlEventTouchUpInside)];
    [_playView.pauseAndPlayBtn addTarget:self action:@selector(didClickPauseAndPlayBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [_playView.nextBtn addTarget:self action:@selector(didClickNextBtn) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_playView];
   
    // 添加tableView
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 250, SCREEN_WIDTH, SCREEN_HEIGHT - 260-110) style:(UITableViewStylePlain)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.mainTableView registerClass:[MQMusicDetailCell class] forCellReuseIdentifier:@"detailCell"];
    self.mainTableView.rowHeight = 60;
    [self.view addSubview:_mainTableView];
    
    [_playView.slider addTarget:self action:@selector(sliderBeginSlide:) forControlEvents:(UIControlEventValueChanged)];
    //选中不显示颜色
//    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];;
    self.mainTableView.backgroundColor = [UIColor clearColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 点击上一曲按钮
- (void)didClickBeforeBtn{
    if (_currentIndex == 0) {
        _currentIndex = self.dataSourceArr.count;
    }
    _currentIndex -= 1;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
    [self tableView:self.mainTableView didSelectRowAtIndexPath:indexPath];

}

#pragma mark 点击暂定/播放按钮
- (void)didClickPauseAndPlayBtn:(UIButton *)sender{
    [[PKPlayerManger shareManger] playAndPause];
  
    if (_playState && sender.selected == NO) {
        [_playView.pauseAndPlayBtn setImage:[UIImage imageNamed:@"zanting"] forState:(UIControlStateNormal)];
        _playState = NO;
        
    }else{
        [_playView.pauseAndPlayBtn setImage:[UIImage imageNamed:@"bofang"] forState:(UIControlStateNormal)];
        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
        _playState = YES;
      
        
    }
      sender.selected = !sender.selected;
    
}

// slider滑动
- (void)timeChange{
    PKPlayerManger *player = [PKPlayerManger shareManger];
    _playView.slider.minimumValue = 0.0;
    _playView.slider.maximumValue = player.finishTime;
    
    NSUInteger yuTime = player.finishTime - player.currentTime;
    NSString *minutes = [NSString stringWithFormat:@"%02ld", yuTime / 60];
    NSString *seconds = [NSString stringWithFormat:@"%02ld", yuTime % 60];
    _playView.timeLabel.text = [[minutes stringByAppendingString:@":"] stringByAppendingString:seconds];
    _playView.slider.value = player.currentTime;
    
    if (player.currentTime !=0 && player.finishTime-player.currentTime==0) {
        [self didClickNextBtn];
        
    }
}
// 跳动到某一个时间点
- (void)sliderBeginSlide:(UISlider *)slider{
    PKPlayerManger *playerManger = [PKPlayerManger shareManger];
    [playerManger seekToTime:slider.value];
    
}

#pragma mark 点击下一曲按钮
- (void)didClickNextBtn{
    _currentIndex += 1;
    if (_currentIndex == self.dataSourceArr.count) {
        _currentIndex = 0;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
    [self tableView:self.mainTableView didSelectRowAtIndexPath:indexPath];
  
}

// 改变cell的指示颜色
- (void)changeSelectedColor{

    for (int i = 0; i < _dataSourceArr.count; i ++) {
        MQMusicDetailModel *model = _dataSourceArr[i];
        MQMusicDetailCell *cell = (MQMusicDetailCell *
                                   )[_mainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if (model.isSelected) {
            cell.showLabel.backgroundColor = [UIColor greenColor];
            model.isSelected = NO;
        }else{
            cell.showLabel.backgroundColor = [UIColor whiteColor];
        }
     
    }
  

}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MQMusicDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MQMusicDetailModel *model = self.dataSourceArr[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    [cell configureCellWithModel:model];
    // Configure the cell...
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    for (int i = 0; i < _dataSourceArr.count; i ++) {
        MQMusicDetailModel *model = _dataSourceArr[i];
        if (i == indexPath.row) {
            model.isSelected = YES;
        }else{
            model.isSelected = NO;
        }
    }
    
    [self changeSelectedColor];
    MQMusicDetailModel *model = self.dataSourceArr[indexPath.row];
    [[PKPlayerManger shareManger] playWithIndex:indexPath.row];
    [_playView configureViewWithModel:model];
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
    model.isSelected = YES;
    _playState = YES;
    _currentIndex = indexPath.row;

   

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    MQMusicDetailCell *cell = (MQMusicDetailCell *)[_mainTableView cellForRowAtIndexPath:indexPath];
    cell.showLabel.backgroundColor = [UIColor whiteColor];
    MQMusicDetailModel *model = self.dataSourceArr[indexPath.row];
    model.isSelected = NO;

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
